import { defineStore } from 'pinia'
import type { User } from '../types'
import { loginApi, getProfileApi, logoutApi } from '../api/auth'

export const useUserStore = defineStore('user', {
  state: () => ({
    user: null as User | null,
    token: localStorage.getItem('token') || '',
    isLoggedIn: false
  }),

  getters: {
    canGenerate: (state) => {
      return state.user ? state.user.used_quota < state.user.daily_quota : false
    },
    
    remainingQuota: (state) => {
      return state.user ? state.user.daily_quota - state.user.used_quota : 0
    }
  },

  actions: {
    async login(loginData: { code?: string; nickname?: string; avatar_url?: string }) {
      try {
        const response = await loginApi(loginData)
        
        this.user = response.user
        this.token = response.token
        this.isLoggedIn = true
        
        localStorage.setItem('token', response.token)
        localStorage.setItem('user', JSON.stringify(response.user))
        
        return { success: true }
      } catch (error: any) {
        return { success: false, error: error.message || '登录失败' }
      }
    },

    async getProfile() {
      try {
        const response = await getProfileApi()
        this.user = response.user
        return { success: true }
      } catch (error: any) {
        return { success: false, error: error.message || '获取用户信息失败' }
      }
    },

    async logout() {
      try {
        await logoutApi()
        
        this.user = null
        this.token = ''
        this.isLoggedIn = false
        
        localStorage.removeItem('token')
        localStorage.removeItem('user')
        
        return { success: true }
      } catch (error: any) {
        // 即使API调用失败，也要清除本地状态
        this.user = null
        this.token = ''
        this.isLoggedIn = false
        
        localStorage.removeItem('token')
        localStorage.removeItem('user')
        
        return { success: true }
      }
    },

    initFromStorage() {
      const token = localStorage.getItem('token')
      const userStr = localStorage.getItem('user')
      
      if (token && userStr) {
        try {
          this.token = token
          this.user = JSON.parse(userStr)
          this.isLoggedIn = true
        } catch (error) {
          // 如果解析失败，清除存储
          localStorage.removeItem('token')
          localStorage.removeItem('user')
        }
      }
    }
  }
})